//
//  HHFlipsideView.m
//  caijing
//
//  Created by czda czda on 12-3-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#define  kViewTagStart 1000
#import "HHFlipsideView.h"
#import "UIView+screenshot.h"
#import "SystemConfiguration.h"
//#import "WiAdView.h"
@interface HHFlipsideView()
{
    //    NSTimer* _animTimer;
    //    CGFloat angle;
}
@property (nonatomic, retain) UIScrollView *contentView;
@property (nonatomic, assign) NSInteger numberOfVisibleItems;
@property (nonatomic, assign) BOOL shouldWrap;
@property (nonatomic, assign) BOOL isAnimationing;
@property (nonatomic, assign) CGFloat itemHeight;
@property (nonatomic, assign) NSInteger currentItemIndex;
@property (nonatomic, assign) CGFloat previousTranslation;
@property (nonatomic, assign) CGFloat panTotal;
- (void)initialize;
- (void)layOutItemViews;
//- (CGFloat)offsetForIndex:(NSInteger)index;
//- (CATransform3D)transformForItemView:(UIView *)view withOffset:(CGFloat)offset;
@end



@implementation HHFlipsideView
@synthesize delegate,dataSource;
@synthesize contentView;
@synthesize numberOfVisibleItems;
@synthesize shouldWrap;
@synthesize itemHeight;
@synthesize perspective;
@synthesize currentItemIndex;
@synthesize isAnimationing;
@synthesize previousTranslation;
@synthesize panTotal;
@synthesize itemCountForShow;
@synthesize TopHeight;
#pragma mark - init
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initialize];
    }
    return self;
}

- (void)awakeFromNib
{
    [self initialize];
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
}
- (void)initialize
{
#ifdef TRACKPAGES
    Class claz = [self class];
    NSString * cname = NSStringFromClass(claz);
    void * p = (void*)self;
    NSString * addr = [NSString stringWithFormat:@"%X",(unsigned int)p];
    [[SystemConfiguration sharedSystemConfiguration] openPageRec:cname  Addr:addr];
#endif
    //    angle = 0;
    numberOfVisibleItems = 0;
    shouldWrap = NO;
    itemHeight = 50;
    TopHeight   = 20;
    perspective = -1.0f/700.0f;//透视
    panTotal = 0.0;
    itemCountForShow = 3;
    contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, self.frame.size.width, self.frame.size.height)];
    contentView.backgroundColor = [UIColor clearColor];
    contentView.showsVerticalScrollIndicator = NO;
    contentView.delegate = self;
    
    [self addSubview:contentView];
    
    [self reloadData];
    
}

#pragma mark - loadData
- (void)reloadData
{
    if (!dataSource || !contentView)
	{
		return;
	}
    for (UIView *view in contentView.subviews)
    {
        [view removeFromSuperview];
    }
    [self layOutItemViews];
}

- (void)layOutItemViews
{
    if (!dataSource || !contentView)
	{
		return;
	}
    
    if ([dataSource respondsToSelector:@selector(numberOfItemsInFlipsideView:)])
    {
        numberOfVisibleItems = [dataSource numberOfItemsInFlipsideView:self];
    }
    
    if (delegate && [delegate respondsToSelector:@selector(flipsideViewShouldWrap:)])
    {
        shouldWrap = [delegate flipsideViewShouldWrap:self];
    }
    else
    {
        shouldWrap = YES;
    }
    
    if (delegate && [delegate respondsToSelector:@selector(flipsideItemHeight:)])
    {
        itemHeight = [delegate flipsideItemHeight:self];
    }
    
    float top = MAX(TopHeight, ((UIViewController *)delegate).view.frame.size.height - (numberOfVisibleItems * itemHeight + 5));
    
    CGRect rect = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, ((UIViewController*)delegate).view.frame.size.height - top);
    
    self.frame = rect;
    contentView.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
    
    contentView.contentSize = CGSizeMake(self.frame.size.width, numberOfVisibleItems * itemHeight + 15);
    
    for (int i = 0;i < numberOfVisibleItems;i++)
    {
        [self buildItemView:i];
    }
    
    currentItemIndex = kViewTagStart;
    
    if (delegate && [delegate respondsToSelector:@selector(flipsideView:didLoadCompleted:)])
    {
        [delegate flipsideView:self didLoadCompleted:currentItemIndex];
    }
}
- (void)buildItemView:(int)index
{
    UIView *view = [dataSource flipsideView:self viewForItemAtIndex:index];
    view.frame = CGRectMake(0,index * view.frame.size.height,view.frame.size.width,view.frame.size.height);
    view.tag = kViewTagStart + index;
    
    if([view isKindOfClass:[UIButton class]])
    {
        UIButton * btn = (UIButton *)view;
        [btn addTarget:self
                action:@selector(clickItem:)
      forControlEvents:UIControlEventTouchUpInside];
    }
    else
    {
        view.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)];
        tapGesture.delegate = (id <UIGestureRecognizerDelegate>)self;
        [view addGestureRecognizer:tapGesture];
        [tapGesture release];
    }
    [self.contentView addSubview:view];
}
#pragma mark - click events
- (void)clickItem:(id)sender
{
    int tag = ((UIButton*)sender).tag;
    if (delegate && [delegate respondsToSelector:@selector(flipsideView:didSelectItemAtIndex:)])
    {
        [delegate flipsideView:self didSelectItemAtIndex:tag - kViewTagStart];
    }
}
- (void)didTap:(UITapGestureRecognizer *)tapGesture
{
    
    NSInteger tag = tapGesture.view.tag;
    NSLog(@"点击tag：%d",tag);
    
    if (delegate && [delegate respondsToSelector:@selector(flipsideView:didSelectItemAtIndex:)])
    {
        [delegate flipsideView:self didSelectItemAtIndex:tag - kViewTagStart];
    }
}
- (void)tapAnimationStop
{
    isAnimationing = NO;
}
//- (void)didPan:(UIPanGestureRecognizer *)panGesture
//{
//    //[[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"wiAdTotal"];
//    
//    //    kIsAdShow;
//    switch (panGesture.state)
//    {
//        case UIGestureRecognizerStateBegan:
//        {
//            previousTranslation = [panGesture translationInView:contentView].y;
//            break;
//        }
//        case UIGestureRecognizerStateEnded:
//        case UIGestureRecognizerStateCancelled:
//        {
//            int total =  (int)(panTotal + 0.5);
//            panTotal = 0.0;
//            if (total!=0)
//            {
//                int index = currentItemIndex - total;
//                if (index >= (numberOfVisibleItems + kViewTagStart))
//                {
//                    index = index - numberOfVisibleItems;
//                }
//                if (index < kViewTagStart)
//                {
//                    //  index = kViewTagStart + numberOfVisibleItems - kViewTagStart - index;
//                    index = kViewTagStart + numberOfVisibleItems - (kViewTagStart - index) -1;
//                }
//                [self scrollToItemAtIndex:index animated:NO];
//                
//            }
//            break;
//        }
//        default:
//        {
//            CGFloat translation = previousTranslation - [panGesture translationInView:contentView].y;
//            panTotal += translation/itemHeight;
//            [self scrollToItemAtIndex:currentItemIndex animated:NO];
//            previousTranslation = [panGesture translationInView:contentView].y;
//        }
//    }
//}

//- (CGFloat)offsetForIndex:(NSInteger)index
//{
//    if (index >= currentItemIndex)
//    {
//        return index - currentItemIndex;
//    }
//    else
//    {
//        return numberOfVisibleItems - (currentItemIndex - index);
//    }
//}


-(void)scrollViewDidScroll:(UIScrollView*)scrollView
{
    CGFloat offset = scrollView.contentOffset.y;
    
    if(1){
        int index = [self indexForOffset:offset];
//        NSLog(@"offset:%f index:%d preindex:%d preangle:%f",offset,index,preIndex_,preAngle_);
        if(index<0) return;
        if(abs(index- preIndex_)>1)
        {
            if(index > preIndex_)
            {
                for (int indexTemp = index -1;indexTemp >preIndex_;indexTemp--) {
                    [self updateItemView:indexTemp angle:0];
//                    NSLog(@"__offset:%f index:%d",offset,indexTemp);
                }
            }
            else
            {
                for (int indexTemp = index +1;indexTemp <preIndex_;indexTemp++) {
                    [self updateItemView:indexTemp angle:0];
//                     NSLog(@"__offset:%f index:%d",offset,indexTemp);
                }
            }
        }
        else if((preAngle_>0 && preAngle_ <M_PI/2) && preIndex_!=index) //可能有漏的，所以要补上复位操作
        {
            [self updateItemView:preIndex_ angle:0];
        }
        CGFloat angle = [self angleForOffset:offset index:index];
//        NSLog(@"angle:%f",angle);
        if((int)(angle*1000)==(int)(preAngle_*1000) && index==preIndex_) //确定精度，不要重复干一个事情
        {
            
        }
        else
        {
            [self updateItemView:index angle:angle];
            preIndex_ = index;
            preAngle_ = angle;
        }
    }
    //old solution
//    if(0){
//        NSInteger index = abs(offset / itemHeight);
//        
//        NSInteger oldIndex = index + 1 > itemCountForShow ? itemCountForShow:index + 1;
//        
//        UIView *view = [scrollView viewWithTag:kViewTagStart + index];
//        UIView *oldview = [scrollView viewWithTag:kViewTagStart + oldIndex];
//        
//        CGFloat os = ((int)(offset * 1000) % (int)(itemHeight * 1000)) / 1000 / itemHeight;
//        
//        //    NSLog(@"offset:%f",os);
//        
//        if(os > 0){
//            view.layer.transform = [self transformForItemView:view withOffset:os];
//            view.alpha = 1- os;
//            if(index != oldIndex){
//                oldview.layer.transform = [self transformForItemView:view withOffset:0];
//                oldview.alpha = 1.0f;
//            }
//        }else{
//            view.layer.transform = [self transformForItemView:view withOffset:0];
//            view.alpha = 1.0f;
//        }
//    }
}
#pragma mark - rotatole
- (void)updateItemView:(int)index angle:(CGFloat)angle;
{
    UIView * currentView = [contentView viewWithTag:kViewTagStart + index];
    
    if(angle>=M_PI/2)
    {
        currentView.alpha = 0;
    }
    else
    {
        //old line
//        currentView.alpha = 1;
        
        //hzh added for changing alpha in rotate view
        currentView.alpha = fabsf(angle / 1.5 - 1);
    }
    CGRect orgFrame  = CGRectMake(0,index * itemHeight,self.frame.size.width,itemHeight);
    //防止出现模糊的情况，重新加载数据
    if(angle==0)
    {
        [self buildItemView:index];
        [currentView removeFromSuperview];
    }
    else
    {
    //        NSLog(@"--- index:%d orgFrame:%@",index,NSStringFromCGRect(orgFrame));
        [self update:currentView angle:angle orgFrame:orgFrame];
    }
}
- (int)indexForOffset:(CGFloat)offsetY
{
    int index = (int) (offsetY /itemHeight);
    if(index<0) return -1;
    
    //    if(offsetY > itemHeight * index)
    //    {
    //        index ++;
    //    }
    return index;
}
-(CGFloat)angleForOffset:(CGFloat)offsetY index:(int)index
{
    if(index<0 || offsetY <= index * itemHeight) return 0;
    
    CGFloat arc = M_PI * itemHeight;
//    CGFloat radius = -15;  //itemHeight / 2.0f / tanf(arc/2.0f/numberOfVisibleItems);
//    CGFloat angleO = offsetY / 1.5 * arc;
//    if (angleO>M_PI * 2.0)
//    {
//        angleO -= M_PI * 2.0;
//    }
//    if (angleO<0)
//    {
//        angleO += M_PI * 2.0;
//    }
//    return angleO;
    
//    //曲线计算，角度偏转,先用线性的测试一下
    CGFloat angleDist = offsetY - index * itemHeight;
    return angleDist/arc * M_PI *2;
//    return floor(angleDist/itemHeight * 90.0f);
}
- (void)update:(UIView*)currentView angle:(CGFloat)angle orgFrame:(CGRect)orgFrame
{
    CGFloat radius = -15;  //itemHeight / 2.0f / tanf(arc/2.0f/numberOfVisibleItems);
    
    if (angle <= M_PI/2 && angle>=0)
    {
//        CGRect orgFrameTemp = currentView.frame;
//        currentView.layer.anchorPoint = CGPointMake(0, 1);
        CATransform3D myTransform = CATransform3DIdentity;
        myTransform.m34 = perspective;
//        myTransform.m34 = -0.006;
        myTransform = CATransform3DRotate(myTransform,angle, 1, 0, 0);

        if ((angle<M_PI/2.0 && angle>=0 ) || (angle>M_PI * 3.0/2.0 && angle<=M_PI * 2.0))
        {
            myTransform = CATransform3DTranslate(myTransform, 0.0f, 0.0f, radius + 0.05f);
        }
        else
            myTransform = CATransform3DTranslate(myTransform, 200.0f, 0.0f, radius + 0.01f);
        
        currentView.layer.transform = myTransform;
        
//        CGRect frame = currentView.frame;
//        
//        //第一次座标会跳，不知道为什么
////        NSLog(@"angle:%f frame:%@",angle,NSStringFromCGRect(frame));
//        //第一次会跳，不知道为什么
//        if( orgFrameTemp.origin.y -frame.origin.y >itemHeight/10)
//        {
//            frame.origin.x = orgFrameTemp.origin.x;
//            frame.origin.y = orgFrameTemp.origin.y +orgFrameTemp.size.height - frame.size.height;
//            currentView.frame = frame;
////            NSLog(@" change angle:%0.0f frame:%@",angle,NSStringFromCGRect(frame));
//        }
        //reset
        if(angle<=0 && (currentView.frame.origin.y != orgFrame.origin.y || currentView.frame.size.height!=orgFrame.size.height))
        {
            currentView.frame = orgFrame;
        }
    }
}
#pragma mark - scroll old solution
//- (void)scrollToItemAtIndex:(NSInteger)index animated:(BOOL)animated
//{
//    if (animated)
//    {
//        isAnimationing = YES;
//        [UIView beginAnimations:@"present-countdown" context:nil];
//        [UIView setAnimationDuration:1.0];
//        [UIView setAnimationDelegate:self];
//        [UIView setAnimationDidStopSelector:@selector(tapAnimationStop)];
//        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//
//        for (int i = 0;i < numberOfVisibleItems;i++)
//        {
//            currentItemIndex =  index;
//            UIView *view = [contentView viewWithTag:kViewTagStart + i];
//            CGFloat offset = [self offsetForIndex:i + kViewTagStart];
//            view.layer.transform = [self transformForItemView:view withOffset:offset];
//            //此处是否需要计算一下偏移，让效果不是从中间翻转？
//        }
//        [UIView commitAnimations];
//    }
//    else
//    {
//        isAnimationing = NO;
//        for (int i = 0;i < numberOfVisibleItems;i++)
//        {
//            currentItemIndex =  index;
//            UIView *view = [contentView viewWithTag:kViewTagStart + i];
//            CGFloat offset = [self offsetForIndex:i + kViewTagStart];
//
//            view.layer.transform = [self transformForItemView:view withOffset:offset];
//
//            //此处是否需要计算一下偏移，让效果不是从中间翻转？
//        }
//    }
//}
#pragma mark - oldSolution
//- (CATransform3D)transformForItemView:(UIView *)view withOffset:(CGFloat)offset
//{
//    CATransform3D transform = CATransform3DIdentity;
//    transform.m34 = perspective;
//    
//    
//    CGFloat arc = M_PI * 2.0f;
//    CGFloat radius = -15;  //itemHeight / 2.0f / tanf(arc/2.0f/numberOfVisibleItems);
//    CGFloat angleO = offset / 1.5 * arc;
//    if (angleO>M_PI * 2.0)
//    {
//        angleO -= M_PI * 2.0;
//    }
//    if (angleO<0)
//    {
//        angleO += M_PI * 2.0;
//    }
//    //    transform = CATransform3DTranslate(transform, 0.0f, 0.0f, -radius);
//    transform = CATransform3DRotate(transform, angleO, 1.0f, 0.0f, 0.0f);
//    
//    if ((angleO<M_PI/2.0 && angleO>=0 ) || (angleO>M_PI * 3.0/2.0 && angleO<=M_PI * 2.0))
//    {
//        return CATransform3DTranslate(transform, 0.0f, 0.0f, radius + 0.05f);
//    }
//    return CATransform3DTranslate(transform, 200.0f, 0.0f, radius + 0.01f);
//}

- (void)dealloc
{
    //    if(cover_)
    //    {
    //        [cover_ removeFromSuperview];
    //        PP_RELEASE(cover_);
    //    }
    self.contentView = nil;
#ifdef TRACKPAGES
    Class claz = [self class];
    NSString * cname = NSStringFromClass(claz);
    void * p = (void*)self;
    NSString * addr = [NSString stringWithFormat:@"%X",(unsigned int)p];
    [[SystemConfiguration sharedSystemConfiguration] closePageRec:cname  Addr:addr];
#endif
    [super dealloc];
}
@end
